package com.hxzy.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hxzy.framework.common.constant.AuthConstant;
import com.nimbusds.jose.JWSObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.ParseException;


/**
 * 认证授权拦截器
 * @author 11452
 */
@Log4j2
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    /**
     * Gateway网关，使用不是springmvc框架( 阻塞式的访问)
     *                   SpringWebFlux 响应式请求框架(非阻塞式的框架) Reactive Streams 响应式流式编程
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求头令牌
        String token = exchange.getRequest().getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER);
        //如果令牌为空，放行其它拦截器来处理(oauth,springsecurity)
        if (StrUtil.isEmpty(token)) {
            //放行
            return chain.filter(exchange);
        }

        try {
            //判断令牌有效性
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            //解析令牌
            JWSObject jwsObject = JWSObject.parse(realToken);
            //取得令牌中的值
            String userStr = jwsObject.getPayload().toString();
            //把令牌对应用户信息，追加到请求头中去
            ServerHttpRequest request = exchange.getRequest().mutate().header(AuthConstant.USER_TOKEN_HEADER, userStr).build();
            exchange = exchange.mutate().request(request).build();
        } catch (ParseException e) {
            //令牌解析失败
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

    /**
     * 拦截器的执行顺序，值越小，执行顺序越靠前
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
